import React, {Component} from 'react'
import './App.css'
import { QueryButton } from '../Button'
import Table from '../Table'
import Search from '../Search'
import { DEFAULT_QUERY, DEFAULT_HPP, BASE_URL, SEARCH_API } from '../../constants'
import './App.css'

class App extends Component {

  constructor(props) {
    super(props)
    this.state = {
      isLoading: false,
      result: null,
      searchKey: DEFAULT_QUERY,
      searchTerm: DEFAULT_QUERY
    }

    this.fetchData = this.fetchData.bind(this)
    this.handlerData = this.handlerData.bind(this)
    this.onMiss = this.onMiss.bind(this)
    this.onSubmit = this.onSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.isFetchData = this.isFetchData.bind(this)
  }

  onMiss(id) {
    const { result, searchKey } = this.state
    const tableRows = result[searchKey].tableRows
    const page = result[searchKey].page
    console.log('newTableRow 2',typeof id)
    console.log('newTableRow 2', tableRows)
    const notId = item => item.id !== id
    const newTableRow = tableRows.filter(notId)
    console.log('newTableRow 2', newTableRow)
    this.setState((prevState) => (
      {
        result: {
          ...prevState.result,
          [searchKey]: { tableRows: newTableRow, page }
        }
      }
    ))
  }

  onSubmit(event) {
    const { searchTerm } = this.state
    this.setState({
      searchKey: searchTerm
    })
    if (this.isFetchData(searchTerm)){
      this.fetchData(searchTerm)
    }
    // 阻止默认行为,默认行为跳转会刷新,导致查询结果混乱
    event.preventDefault()
  }

  onChange(event) {
    this.setState({
      searchTerm: event.target.value
    })
  }

  componentDidMount() {
    const { searchTerm } = this.state
    this.fetchData(searchTerm)
  }

  isFetchData(searchTerm) {
    return !this.state.result[searchTerm]
  }

  fetchData(searchTerm, page = 0) {
    this.setState({
      isLoading: true
    })
    const url = `${BASE_URL}${SEARCH_API}?query=${searchTerm}&page=${page}&hitsPerPage=${DEFAULT_HPP}`
    fetch(url)
      .then(res => res.json())
      .then(json => this.handlerData(json))
      .finally(() => {
        this.setState({
          isLoading: false
        })
      })
  }

  handlerData(json) {
    const { hits, page } = json
    const { searchKey } = this.state
    let tableRows = []
    hits.forEach(item => {
      const { objectID, title, author, num_comments, points } = item
      const tableRow = {
        id: objectID,
        title: title,
        author: author,
        comments: num_comments,
        points: points
      }
      tableRows.push(tableRow)
    })
    // state中对之前数据叠加,使用这种方式setState
    this.setState((prevState) => (
      {
        result: {
          ...prevState.result,
          [searchKey]: { tableRows, page }
        }
      }
    ))
  }


  render() {
    const { result, searchTerm, searchKey, isLoading } = this.state
    const tableRows = (result && (result[searchKey]) && result[searchKey].tableRows)
                      || []
    const page = (result && (result[searchKey]) && result[searchKey].page)
                    || 0
    console.log('render', searchKey)
    console.log('render', page)
    return (
      <div className='app'>
        <Search value={searchTerm} onSubmit={this.onSubmit} onChange={this.onChange}>查询</Search>
        <Table tableRows={tableRows} onMiss={this.onMiss} />
        <QueryButton isLoading={isLoading} onClick={() => this.fetchData(searchKey, page + 1)}>more</QueryButton>
      </div>
    )
  }
}

export default App
